package com.itheima.app.manager;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.itheima.app.interceptor.UserHolder;
import com.itheima.domain.db.UserInfo;
import com.itheima.domain.mongo.FocusUser;
import com.itheima.domain.mongo.Video;
import com.itheima.service.db.UserInfoService;
import com.itheima.service.mongo.FocusUserService;
import com.itheima.service.mongo.VideoService;
import com.itheima.util.ConstantUtil;
import com.itheima.vo.PageBeanVo;
import com.itheima.vo.VideoVo;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Component
public class VideoManager {

    @DubboReference
    VideoService videoService;

    @DubboReference
    UserInfoService userInfoService;

    @Autowired
    FastFileStorageClient client;

    @Autowired
    FdfsWebServer server;

    @DubboReference
    FocusUserService focusUserService;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    //推荐视频列表
    @Cacheable(value = "tanhua",key = "#userId+'_'+#pageNum+'_'+#pageSize")// 99_1_10
    public PageBeanVo findRecommendVideoByPage(Long userId, Integer pageNum, Integer pageSize) {
        System.out.println("------------------------------------");

        //2.远程调用service查询pageBeanVo
        PageBeanVo pageBeanVo = videoService.findRecommendVideoByPage(userId, pageNum, pageSize);

        //3.获取分页对象中的视频集合,遍历,获取每个视频对象,获取视频发布者userInfo,将video和userInfo封装videoVO对象,将vo对象放入vo集合中
        List<Video> items = (List<Video>) pageBeanVo.getItems();

        List<VideoVo> voList = new ArrayList<>();

        if (CollUtil.isNotEmpty(items)) {
            items.forEach(v->{
                // 获取视频发布者userInfo,
                UserInfo userInfo = userInfoService.findByUserId(v.getUserId());

                // 将video和userInfo封装videoVO对象,
                VideoVo vo = new VideoVo();
                // 先封装userInfo再封装视频
                vo.setUserInfo(userInfo);
                vo.setVideo(v);

                //判断是否关注用户
                if(stringRedisTemplate.hasKey(StrUtil.format(ConstantUtil.FOCUS_USER,userId,v.getUserId()))){
                    vo.setHasFocus(1);
                }

                // 将vo对象放入vo集合
                voList.add(vo);
            });
        }

        //4.将vo集合设置给pageBeanVo
        pageBeanVo.setItems(voList);
        //5.返回pageBeanVo
        return pageBeanVo;
    }

    //@CacheEvict(value = "tanhua",allEntries = true)
    @CacheEvict(value = "tanhua",key = "#userId+'_*'")
    public void save(Long userId, MultipartFile videoThumbnail, MultipartFile videoFile) throws IOException {
        //1.将封面和视频上传到FastDFS上,获取路径
        StorePath coverPath = client.uploadFile(videoThumbnail.getInputStream(), videoThumbnail.getSize(), FileUtil.extName(videoThumbnail.getOriginalFilename()), null);
        StorePath videoPath = client.uploadFile(videoFile.getInputStream(), videoFile.getSize(), FileUtil.extName(videoFile.getOriginalFilename()), null);

        //2.创建video对象,封装video
        Video video = new Video();

        video.setCreated(System.currentTimeMillis());
        video.setUserId(userId);
        video.setPicUrl(server.getWebServerUrl()+coverPath.getFullPath());
        video.setVideoUrl(server.getWebServerUrl()+videoPath.getFullPath());

        System.out.println(video.getVideoUrl());
        System.out.println(video.getPicUrl());

        //3.远程调用service完成保存操作
        videoService.save(video);
    }

    public void focusUser(Long focusUserId) {
        //1.获取当前登陆者id
        Long userId = UserHolder.get().getId();

        //2.创建FocusUser对象且封装
        FocusUser focusUser = new FocusUser();
        focusUser.setCreated(System.currentTimeMillis());
        focusUser.setUserId(userId);
        focusUser.setFocusUserId(focusUserId);

        //3.远程调用service完成操作
        focusUserService.save(focusUser);

        //4.添加关注的标记(redis)  //  focus_user:用户id_被关注的用户id
        stringRedisTemplate.opsForValue().set(StrUtil.format(ConstantUtil.FOCUS_USER,userId,focusUserId),"1");
    }

    public void unFocusUser(Long focusUserId) {
        //1.获取当前登陆者id
        Long userId = UserHolder.get().getId();

        //2.远程调用service完成删除操作
        focusUserService.delete(userId,focusUserId);

        //3.删除关注的标记(redis)
        stringRedisTemplate.delete(StrUtil.format(ConstantUtil.FOCUS_USER,userId,focusUserId));
    }
}
